<?php
/**
 * 
 */

namespace app\lib\weixin;

/**
 * 微信通用基础类库
 */
class Weixin {

    /**
     * curl get 请求
     * @param $url
     * @return mixed
     */
    public static  function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    /**
     * curl post 请求
     * @param $post_data
     * @param $url
     * @return mixed
     */
    public function httpPost($post_data, $url) {
        $http_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_USERAGENT, $http_user_agent); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
     /**
     * 获取职背调用户的access_token
     * @return mixed
     */
    public function getAccessToken() {
        //从数据库获取用户的公众账户信息
        $redis_key = 'wx:shangquan:accesstoken';
        //从数据库获取用户的公众账户信息
        $appid  = config("config.wx.appid");
        $secret = config("config.wx.secret");
        /*
         * 正式版redis
         */
        $redis = Redis::connection('redis_release');
        $wx_arr = $redis->get($redis_key);
        if(isset($wx_arr) && !empty($wx_arr)){
            $wx_arr = json_decode($wx_arr,true);
            if (time() > $wx_arr['tokentime'] + 7000 || empty($wx_arr['tokentime'])) {

                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;

                $res = json_decode($this->httpGet($url));

                $access_token = $res->access_token;
                if ($access_token) {
                    $wxaccess_arr['tokentime'] = time();
                    $wxaccess_arr['accesstoken'] = $access_token;
                    //更新用户信息表里面的token信息
                    $redis->set($redis_key,json_encode($wxaccess_arr),'EX',7000);
                }
            } else {

                $access_token = $wx_arr['accesstoken'];
            }
        }else{
             $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;

                $res = json_decode($this->httpGet($url));
                $access_token = $res->access_token;
                if ($access_token) {
                    $wxaccess_arr['tokentime'] = time();
                    $wxaccess_arr['accesstoken'] = $access_token;
                    //更新用户信息表里面的token信息
                    $redis->set($redis_key,json_encode($wxaccess_arr),'EX',7000);
                }
        }
        return $access_token;
    }

    /**
     * 小程序门店专用，获取用户ID
     * @param $code string 小程序传过来的code用来获取openid
     * @return mixed string
     */
    public function getUserInfo($openid){

        $access_token = $this->getAccessToken();

        $api    = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN"; //调用官方接口
        $data = $this->httpGet($api);
        $data = json_decode($data,true);
        return $data;
    }

    //获取小程序openid
    public function getOpenID($code,$type='wx'){
        if($type=='wx'){
            $appid=config('config.wx.appid');
            $secret=config('config.wx.secret');
            $url    = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';
            $result = httpGet($url);
            $res    = json_decode($result, true);
            return $res;
        }
    }

    /*
     * 解析小程序手机号
     * @param  [type] $encrypted_data
     * @param  [type] $session_key
     * @param  [type] $iv
     * @return [type]         [description]
     */
    public function wxAnalysisPhone($encrypted_data, $session_key, $iv) {
        $aesCipher = base64_decode($encrypted_data);
        $aesKey    = base64_decode($session_key);
        $aesIV     = base64_decode($iv);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        //这里再次判断一次的原因是因为  重新生成的session_key  第一次解密会出现返回false的情况  第二次就正常  so.....
        if ($result == false) {
            $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        }

        $result = json_decode($result, true);
        if (!isset($result['phoneNumber'])) {
            //错误返回false
            return false;
        }
        return $result;
    }



}